//
//  KKPictureSelectorController.swift
//  SinaWeiBo
//
//  Created by King.Kong. on 16/5/30.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit
import SVProgressHUD
import HMImagePicker
//定义显示图片的信息
private let colCount: CGFloat = 4
private let margin: CGFloat = 3
private let maxImageCount = 4
private let itemWidth: CGFloat = (ScreenWidth - (colCount + 1) * margin) / colCount
//定义可重用标识符
let PictureCellId = "PictureCellId"
class KKPictureSelectorController: UICollectionViewController {

    //声明数组
    lazy var selectedAsset: [PHAsset] = [PHAsset]()
    //定义图片的数组
    lazy var images: [UIImage] = [UIImage]()

    init() {
        let layout = UICollectionViewFlowLayout()
        //设置itemSize
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //设置行列的间距
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        //设置每组的内间距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        super.init(collectionViewLayout: layout)
        // 注册
        self.collectionView?.registerClass(KKPictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellId)
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        
    }
        required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// 数据源方法
extension KKPictureSelectorController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = images.count == maxImageCount ? 0 : 1
        
        return images.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! KKPictureSelectorCell
        cell.backgroundColor = randomColor()
        if indexPath.item == images.count {
            //获取数组中的最后一个数据
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
        }
        // 友情提示
        if images.count == maxImageCount {
            SVProgressHUD.showInfoWithStatus("已达到最大可选张数了")
        }
        
        cell.selectorDelegate = self
        return cell
    }
}

extension KKPictureSelectorController: KKPictureSelectorCellDelegate {
    func userWillAddPicture() {
        print("添加图片")
        //图片选择器 是系统的
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            //如果没有访问权限
            print("没有访问权限")
            return
        }
        
        
        let picker = HMImagePickerController(selectedAssets: selectedAsset)
        picker.pickerDelegate = self
        picker.targetSize = CGSize(width: 600, height: 600)
        picker.maxPickerCount = maxImageCount
        presentViewController(picker, animated: true, completion: nil)

        
//        let picker = UIImagePickerController()
//        //使用modal的方式展现图片选择
//        picker.delegate = self
//        //设置图片可以被编辑
////        picker.allowsEditing = true
//         self.presentViewController(picker, animated: true, completion: nil)

    }
    func userWillDeletePicture(cell: KKPictureSelectorCell) {
        print("删除图片")
        //需要知道删除的是哪一张图片
        //1.如何获取点击的按钮所在cell 协议方法的参数中获取
        //2.通过cell获取对应的indexPath
        guard let indexPath = collectionView?.indexPathForCell(cell) else {
            return
        }
        //3.需要indexPath 删除数组对应的数据
        images.removeAtIndex(indexPath.item)
        //3.1 删除记录选中资源集合中的元素
        selectedAsset.removeAtIndex(indexPath.item)
        //4.操作完数据源之后 刷新collectionView
        collectionView?.reloadData()
    }
}

extension KKPictureSelectorController: HMImagePickerControllerDelegate {
    
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        self.images = images
        //记录选中资源集合，方便再次选择照片定位
        self.selectedAsset = selectedAssets!
        self.collectionView?.reloadData()
        self.dismissViewControllerAnimated(true, completion: nil)
       
    }
}

//定义协议
@objc protocol KKPictureSelectorCellDelegate: NSObjectProtocol {
    //定义协议方法
    optional func userWillAddPicture()
    
    optional func userWillDeletePicture(cell: KKPictureSelectorCell)

}
// 自定义cell
class KKPictureSelectorCell:UICollectionViewCell {
    var image: UIImage? {
        didSet {
            //完成给按钮设置图片
            //隐藏添加按钮没有图片的时候的删除按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    //代理对象的属性  要使用 weak 表示弱引用
    weak var selectorDelegate: KKPictureSelectorCellDelegate?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 按钮的点击事件
    @objc private func addBtnDidClick() {
        if image != nil {
            SVProgressHUD.showInfoWithStatus("已经添加了图片啦,不要再点啦")
            return
        }
        selectorDelegate?.userWillAddPicture?()
        return
    }
    
    
    @objc private func deleteBtnDidClick() {
        selectorDelegate?.userWillDeletePicture?(self)
        
    }
    
    //设置界面
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        
        //添加按钮的点击事件
        addBtn.addTarget(self, action: #selector(KKPictureSelectorCell.addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(KKPictureSelectorCell.deleteBtnDidClick), forControlEvents: .TouchUpInside)
    }

    
    //懒加载控件
    private lazy var addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_pic_add"), forState: .Normal)
        btn.imageView?.contentMode = .ScaleAspectFill
        //手动设置裁剪父视图
        btn.imageView?.clipsToBounds = true
        return btn
    }()
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        return btn
    }()

    
    
}









